package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.dispatch.bean.fob.SpFobLabelGroup;
import com.ship.dispatch.bean.fob.SpFobLabelItem;
import com.ship.dispatch.mapper.fob.SpFobLabelGroupMapper;
import com.ship.dispatch.mapper.fob.SpFobLabelItemMapper;
import com.ship.dispatch.service.fob.SpFobLabelGroupService;
import com.ship.dispatch.service.fob.SpFobLabelItemService;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.vo.fileTemplate.SpFobLabelItemVO;
import liquibase.pro.packaged.S;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobLabelGroupServiceImpl
 * @description
 * @create 2023/12/23 0023
 */
@Service
public class SpFobLabelItemServiceImpl extends BaseServiceImpl<SpFobLabelItemMapper, SpFobLabelItem> implements SpFobLabelItemService {

    @Autowired(required = false)
    SpFobLabelGroupMapper spFobLabelGroupMapper;



    @Override
    public Map<String, String> getLabelKesData(String nodeKey,List<String> labels,String instanceId) {
         List<SpFobLabelItem> list = this.baseMapper.selectList(new LambdaQueryWrapper<SpFobLabelItem>().in(SpFobLabelItem::getLabelName,labels).and(qr->qr.eq(SpFobLabelItem::getNodeKey,nodeKey).or().eq(SpFobLabelItem::getNodeKey,"public")));
         Map<Long,List<SpFobLabelItem>> maps = list.stream().collect(Collectors.groupingBy(SpFobLabelItem::getGroupId));
         Map<String,String> resultMap = new HashMap<>();

        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
        DateTimeFormatter inputFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outputFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}");
        Pattern pattern2 = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$");


        // 封装获取全部数据
         for(Long groupId:maps.keySet()){
             List<SpFobLabelItem> items = maps.get(groupId);
             if(items.size()>1){ // 同一个分组多个字段，获取分组sql 查询
                 SpFobLabelGroup  spFobLabelGroup = spFobLabelGroupMapper.selectById(groupId);
                 if(spFobLabelGroup.getGroupSql()!=null){
                     Map<String,String> tempap =   spFobLabelGroupMapper.selectGroupSql(spFobLabelGroup.getGroupSql(),instanceId);
                     if(tempap==null) continue;
//                     for(SpFobLabelItem item:items){
//                         if(tempap.get(item.getLabelKey())!=null && tempap.get(item.getLabelKey())!=""){
//                             if (){
//
//                                 tempap.get(item.getLabelKey());
//                                 resultMap.put(item.getLabelName(), tempap.get(item.getLabelKey()));
//                             }else {
//                                 resultMap.put(item.getLabelName(), tempap.get(item.getLabelKey()));
//                             }
//                         }
//                     }
                     for (SpFobLabelItem item : items) {
                         Object value = tempap.get(item.getLabelKey()); // 使用 Object 类型接收值

                         if (value != null) {
                             String labelValue = value.toString(); // 将值转换为字符串

                             if (!labelValue.isEmpty()) {
                                 Matcher matcher = pattern.matcher(labelValue);
                                 Matcher matcher1 = pattern2.matcher(labelValue);
                                 if (matcher.matches() || matcher1.matches()) {
                                     if (labelValue.contains("T")){
                                         labelValue = labelValue.replaceAll("T"," ");
                                     }
                                     if(labelValue.contains("00:00:00")){
                                         labelValue = labelValue.replaceAll("00:00:00","");
                                     }
                                     if(labelValue.contains("00:00")){
                                         labelValue = labelValue.replaceAll("00:00","");
                                     }
                                     try {
                                         LocalDateTime dateTime = LocalDateTime.parse(labelValue, inputFormatter);
                                         resultMap.put(item.getLabelName(), dateTime.format(outputFormatter));
                                     } catch (DateTimeParseException e) {
                                         try {
                                             LocalDateTime dateTime = LocalDateTime.parse(labelValue, inputFormatter1);
                                             resultMap.put(item.getLabelName(), dateTime.format(outputFormatter2));
                                         } catch (DateTimeParseException e1) {
                                             // 处理日期解析异常
                                             System.err.println("日期解析异常：" + e.getMessage());
                                             resultMap.put(item.getLabelName(), labelValue); // 将原始值放入 resultMap
                                         }
                                     }
                                 } else {
                                     resultMap.put(item.getLabelName(), labelValue);
                                 }
                             }
                         }
                     }
                 }
             }else { // 直接查询标签sql
                SpFobLabelItem item = maps.get(groupId).get(0);
                if(item.getLabelSql()!=null){
                    Object result = spFobLabelGroupMapper.selectLabelSql(item.getLabelSql(),instanceId);
                    if(result!=null && result!=""){
                        String newValue = result.toString();
                        Matcher matcher = pattern.matcher(newValue);
                        Matcher matcher1 = pattern2.matcher(newValue);
                        if (matcher.matches() || matcher1.matches()) {
                            if (newValue.contains("T")){
                                newValue = newValue.replaceAll("T"," ");
                            }
                            if(newValue.contains("00:00:00")){
                                newValue = newValue.replaceAll("00:00:00","");
                            }
                            if(newValue.contains("00:00")){
                                newValue = newValue.replaceAll("00:00","");
                            }
                            try {
                                LocalDateTime dateTime = LocalDateTime.parse(newValue, inputFormatter);
                                resultMap.put(item.getLabelName(), dateTime.format(outputFormatter));
                            } catch (DateTimeParseException e) {
                                try {
                                    LocalDateTime dateTime = LocalDateTime.parse(newValue, inputFormatter1);
                                    resultMap.put(item.getLabelName(), dateTime.format(outputFormatter2));
                                } catch (DateTimeParseException e1) {
                                    // 处理日期解析异常
                                    System.err.println("日期解析异常：" + e.getMessage());
                                    resultMap.put(item.getLabelName(), newValue); // 将原始值放入 resultMap
                                }
                            }
                        } else {
                            resultMap.put(item.getLabelName(), newValue);
                        }
                    }
                }
             }
         }
         resultMap.put("当前用户名", SecurityUtils.getUsername());
         resultMap.put("当前用id", SecurityUtils.getStringUserId());
        return resultMap;
    }

    public static boolean isValidDateTime(String dateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            LocalDateTime.parse(dateTime, formatter);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
    /**
     * 获取所有可用标签
     * @param name
     * @return
     */
    @Override
    public List<SpFobLabelItemVO> getSpFobLabelItems(String name){
        List<SpFobLabelItemVO> fobLabelItemVOS = new ArrayList<>();
        LambdaQueryWrapper<SpFobLabelItem> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)){
            queryWrapper.like(SpFobLabelItem::getLabelName,"%"+name+"%");
        }
        List<SpFobLabelItem> labelItems = this.list(queryWrapper);
        if(null != labelItems && labelItems.size()>0){
            labelItems.stream().forEach(p->{
                String labelNew = String.format("%s"+p.getLabelName()+"%s","${","}");
                SpFobLabelItemVO fobLabelItemVO = new SpFobLabelItemVO();
                fobLabelItemVO.setLabel(labelNew);
                fobLabelItemVO.setLabelKey(p.getLabelKey());
                if(null == fobLabelItemVOS){
                    fobLabelItemVOS.add(fobLabelItemVO);
                }else{
                    if(fobLabelItemVOS.stream().filter(n->n.getLabel().equals(labelNew)).count()==0){
                        fobLabelItemVOS.add(fobLabelItemVO);
                    }
                }
            });
        }
        return fobLabelItemVOS;
    }
}
